// EMS数据拉取服务
import { ElMessage } from 'element-plus'

export interface FetchResult {
    success: boolean
    message: string
    data?: any
    timestamp: string
}

// 调用Python爬虫脚本获取最新EMS数据
export const fetchLatestEMSData = async (): Promise<FetchResult> => {
    try {
        console.log('开始调用Python爬虫脚本获取最新EMS数据...')

        // 方案1: 调用后端API（推荐）
        try {
            const response = await fetch('/api/fetch-ems-data', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    action: 'run_scraper',
                    script: 'japanpost_ems_scraper_working.py'
                })
            })

            if (response.ok) {
                const result = await response.json()
                if (result.success) {
                    return {
                        success: true,
                        message: '成功获取最新EMS运费数据',
                        data: result.data,
                        timestamp: new Date().toLocaleString('zh-CN')
                    }
                }
            }
        } catch (apiError) {
            console.log('API调用失败，尝试其他方案:', apiError)
        }

        // 方案2: 调用本地Python脚本（需要后端支持）
        try {
            const response = await fetch('http://localhost:5001/run-scraper', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    script: 'japanpost_ems_scraper_working.py'
                })
            })

            if (response.ok) {
                const result = await response.json()
                return {
                    success: true,
                    message: 'Python爬虫脚本执行成功',
                    data: result.data,
                    timestamp: new Date().toLocaleString('zh-CN')
                }
            }
        } catch (localError) {
            console.log('本地Python脚本调用失败:', localError)
        }

        // 方案3: 如果都失败了，提示用户手动运行脚本
        throw new Error('无法自动调用Python爬虫脚本，请手动运行: python3 japanpost_ems_scraper_working.py')

    } catch (error) {
        console.error('调用Python爬虫脚本失败:', error)
        return {
            success: false,
            message: `获取数据失败: ${error instanceof Error ? error.message : '未知错误'}`,
            timestamp: new Date().toLocaleString('zh-CN')
        }
    }
}

// 验证数据完整性
export const validateEMSData = (data: any): boolean => {
    if (!data || !data.zones || !data.freightData) {
        return false
    }

    // 检查区域数据
    if (!Array.isArray(data.zones) || data.zones.length === 0) {
        return false
    }

    // 检查运费数据
    if (!Array.isArray(data.freightData) || data.freightData.length === 0) {
        return false
    }

    // 检查每个运费数据项的结构
    for (const item of data.freightData) {
        if (!item.weight || !item.weight_text || !item.prices) {
            return false
        }

        // 检查价格数据
        if (typeof item.prices !== 'object' || Object.keys(item.prices).length === 0) {
            return false
        }
    }

    return true
}

// 数据对比功能
export const compareData = (oldData: any, newData: any): {
    hasChanges: boolean
    changes: string[]
    newItems: number
    updatedItems: number
} => {
    const changes: string[] = []
    let newItems = 0
    let updatedItems = 0

    if (!oldData || !newData) {
        return { hasChanges: true, changes: ['数据格式发生变化'], newItems: 0, updatedItems: 0 }
    }

    // 检查区域变化
    if (oldData.zones?.length !== newData.zones?.length) {
        changes.push(`区域数量从 ${oldData.zones?.length || 0} 变为 ${newData.zones?.length || 0}`)
    }

    // 检查运费数据变化
    if (oldData.freightData?.length !== newData.freightData?.length) {
        changes.push(`运费数据从 ${oldData.freightData?.length || 0} 条变为 ${newData.freightData?.length || 0} 条`)
    }

    // 检查价格变化
    if (oldData.freightData && newData.freightData) {
        for (const newItem of newData.freightData) {
            const oldItem = oldData.freightData.find((item: any) => item.weight === newItem.weight)

            if (!oldItem) {
                newItems++
                changes.push(`新增重量等级: ${newItem.weight_text}`)
            } else {
                // 检查价格变化
                for (const zone in newItem.prices) {
                    if (oldItem.prices[zone] !== newItem.prices[zone]) {
                        updatedItems++
                        changes.push(`${newItem.weight_text} - ${zone} 价格从 ${oldItem.prices[zone]} 变为 ${newItem.prices[zone]} 日元`)
                    }
                }
            }
        }
    }

    return {
        hasChanges: changes.length > 0,
        changes,
        newItems,
        updatedItems
    }
}

// 保存数据到本地存储
export const saveDataToStorage = (data: any, key: string = 'ems_freight_data'): boolean => {
    try {
        const dataToSave = {
            ...data,
            lastUpdated: new Date().toISOString(),
            version: '1.0.0'
        }

        localStorage.setItem(key, JSON.stringify(dataToSave))
        return true
    } catch (error) {
        console.error('保存数据到本地存储失败:', error)
        return false
    }
}

// 从本地存储加载数据
export const loadDataFromStorage = (key: string = 'ems_freight_data'): any | null => {
    try {
        const stored = localStorage.getItem(key)
        if (stored) {
            return JSON.parse(stored)
        }
        return null
    } catch (error) {
        console.error('从本地存储加载数据失败:', error)
        return null
    }
}
